package view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import util.DBUtil;
import db.ItemType;

public class DrawCatalog {

	public ItemType selectedItemType;
	private Map<Long, List<ItemType>> itemTypesMap = new HashMap<Long, List<ItemType>>();

	public ItemType getCatalog(int item_type_id) {
		DBUtil eventManager = new DBUtil();
		ItemType ItemTypeCatalog = null;
		ItemTypeCatalog = eventManager.getItemTypeById(item_type_id);
		return ItemTypeCatalog;
	}

	public String drawCatalog(ItemType itemType, int selected_catalog_id) {
		String catalog_out = "";
		String selected_indicator = "";
		if (selected_catalog_id == itemType.getItemType()) {
			this.selectedItemType = itemType;
			selected_indicator = "id = 'selected'";
		}
		ItemType subcatalog = null;
		for (int i = 0; i < (itemType.getLevel() - 1); i++) {
			catalog_out = catalog_out + "--";
		}
		catalog_out = catalog_out  + "<a "+ selected_indicator +" href=\"?catalog="
				+ itemType.getItemType() + "\"> " + itemType.getTypeName()
				+ "</a><br>\n";
		
		if(itemTypesMap.containsKey(itemType.getItemType())){
		    Iterator<ItemType> iter = itemTypesMap.get(itemType.getItemType()).iterator();
			while (iter.hasNext()) {
				subcatalog = (ItemType) iter.next();
				catalog_out = catalog_out
						+ drawCatalog(subcatalog, selected_catalog_id);
			}
		}
		
		return catalog_out;
	}
	
	public String DrawCatalogTree(int selected_catalog_id) {
		DBUtil eventManager = new DBUtil();
		List<ItemType> allCatalogs = eventManager.getAllCatalogs();
		String catalog_out = "";
		
		for (ItemType item : allCatalogs) {
		    if(itemTypesMap.containsKey(item.getItemType_1())){
			itemTypesMap.get(item.getItemType_1()).add(item);
		    }else{
			List<ItemType> itemTypes = new ArrayList<ItemType>();
			itemTypes.add(item);
			itemTypesMap.put(item.getItemType_1(), itemTypes);
		    } 
		}

		for (ItemType item : allCatalogs) {
		    if(item.getLevel().equals(1L)){
			catalog_out = catalog_out
				+ drawCatalog(item, selected_catalog_id);
		    }			
		}
		return catalog_out;

	}

}
